<?php
namespace maowenke\mysql;
/**
 * Mysql备份类
 */
class Restore {
	/**
	 * 数据库配置
	 * @var array
	 */
	protected $database = [];

	/**
	 * pdo连接对象
	 * @var null
	 */
	protected $pdo = null;
	
	protected $error = '';
	/**
	 * 构造方法
	 * @param array $database
	 * 	[
	 * 		'username'=>'',
	 * 		'password'=>'',
	 * 		'database'=>'',
	 * 		'host'=>''
	 * 	]
	 */
	public function __construct($database) {
		$this->database = $database;
	}
    
	/**
	 * 连接数据库
	 */
	private function getConnection(){
		$dsn = 'mysql:host='.$this->database['host'].';dbname='.$this->database['database'];
		$username = $this->database['username'];
		$password = $this->database['password'];
		$driver_options = [
			\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
			\PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
		];

		try{
			$this->pdo = new \PDO($dsn, $username, $password, $driver_options);
		} catch (\PDOException $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * 还原数据库
	 * @param  string $file 文件路径
	 * @return bool       [description]
	 */
	public function restore($file){
		/*建立链接*/
		$this->getConnection();

		/*获取SQL*/
		$sql_arr = $this->getSqls($file);
		if (false === $sql_arr) {
			return false;
		}
		
		/*循环执行*/
		foreach ($sql_arr as $sql) {
			if (!$this->pdo->exec($sql)) {
				if ("00000" !== $this->pdo->errorCode()) {
					$err = $this->pdo->errorInfo();
					$this->error = $err[0]." ".$err[1]." ".$err[2];
				return false;
				};
//				var_dump($sql);
			};	
		}
		return true;
	}

	/**
	 * 获取sql数组
	 * @param  string $file 文件路径
	 * @return mixed       [description]
	 */
	private function getSqls($file){
		if (!file_exists($file)) {
			$this->error = 'sql 文件不存在！';
			return false;
		}
		$sql = file_get_contents($file);
		$sql = str_replace("\r", "\n", $sql);
		$sql = trim($sql);
		$sql = str_replace('__PREFIX__',$this->database['prefix']??'',$sql);
		$sql_arr = explode(";\n", $sql);
		return $sql_arr;
	}

	public function getError(){
		return $this->error;
	}

	/**
	 * 释放连接
	 */
	private function releaseConnection() {
		$this->pdo = null;
	}

	/**
	 * 析构方法
	 */
	public function __destruct() {
		$this->releaseConnection();
	}
}